package com.chendx.store.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.model.common.enums.AppHttpCodeEnum;
import com.chendx.model.user.dto.LoginDto;
import com.chendx.model.user.pojo.User;
import com.chendx.store.common.constants.user.LoginContanst;
import com.chendx.store.user.mapper.UserMapper;
import com.chendx.store.user.service.UserLoginService;
import com.chendx.store.utils.common.AppJwtUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * Created by chendx on 2022/4/26.
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //1.校验参数
        if (dto.getPhone() == null
                && (StringUtils.isEmpty(dto.getPassword()) && StringUtils.isEmpty(dto.getPassword()))) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //用户名密码登录
        if (!StringUtils.isEmpty(dto.getUsername()) && !StringUtils.isEmpty(dto.getPassword())) {
            User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, dto.getUsername()));
            if (user != null) {
                String pswd = DigestUtils.md5Hex((dto.getPassword() + user.getSalt()).getBytes());
                if (pswd.equals(user.getPassword())) {
                    Map<String, Object> map = new HashMap<>();
                    user.setPassword("");
                    user.setSalt("");
                    map.put("user", user);
                    map.put("userId", user.getId());
                    map.put("username", user.getUsername());
                    map.put("headpic", user.getHeadPic());
                    map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
                    return ResponseResult.okResult(map);
                } else {
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
        } else if (!StringUtils.isEmpty(dto.getPhone())) {
            if (StringUtils.isEmpty(dto.getCode())) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getPhone, dto.getPhone()));
            if (user == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PHONE_IS_NOT_REGISTER);
            }
            Boolean flag = checkvCode(dto.getPhone(), dto.getCode());
            if (!flag) {
                return ResponseResult.errorResult(AppHttpCodeEnum.VCODE_INVALID);
            }
            redisTemplate.delete(LoginContanst.LOGIN_VER_CODE + user.getPhone());
            Map<String, Object> map = new HashMap<>();
            user.setPassword("");
            user.setSalt("");
            map.put("user", user);
            map.put("userId ", user.getId());
            map.put("username ", user.getUsername());
            map.put("token", AppJwtUtil.getToken(user.getId().longValue()));
            return ResponseResult.okResult(map);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
    }


    @Override
    public ResponseResult verficationCode(LoginDto dto) {
        //1.校验参数
        if (dto == null || StringUtils.isEmpty(dto.getPhone())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Random random = new Random();
        String code = random.nextInt(9999) + "";
        redisTemplate.opsForValue().set(LoginContanst.LOGIN_VER_CODE + dto.getPhone(), code, 5 * 60 * 1000, TimeUnit.MILLISECONDS);
        return ResponseResult.okResult(code);
    }

    @Override
    public Boolean checkvCode(String phone, String code) {
        String vcode = redisTemplate.opsForValue().get(LoginContanst.LOGIN_VER_CODE + phone);
        if (!code.equals(vcode)) {
            return false;
        }
        return true;
    }

}
